package com.cskaoyan._02tostring;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/14 15:11
 **/
/*
    源码:
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

    说明:
        getClass().getName() : 全类名
        Integer.toHexString(hashCode()) : 十六进制地址值
    作用:
        返回该对象的字符串表示
 */
public class Demo {
    public static void main(String[] args) {
        Student student = new Student("zs", 20);
        System.out.println(student);
        // com.cskaoyan._02tostring.Student@1b6d3586
        // println会自动调用toString方法

        // 重写toString之后再执行
        System.out.println(student);
        // Student{name='zs', age=20}

        Student s = new Student("ls", 21);
        s = null;
        System.out.println(s);
        // System.out.println(s.toString());

        System.out.println("-------------");
        Teacher teacher = new Teacher("张老师", 30, new Subject("数学"));
        System.out.println(teacher);
    }
}

class Student{
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 重写Object中的toString()方法

    @Override
    public String toString() {
        return "Student[" +
                "name='" + name + '\'' +
                ", age=" + age +
                ']';
    }
}

class Teacher{
    String name;
    int age;
    Subject subject;

    public Teacher(String name, int age, Subject subject) {
        this.name = name;
        this.age = age;
        this.subject = subject;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", subject=" + subject +
                '}';
    }
}

class Subject{
    String name;

    public Subject(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Subject{" +
                "name='" + name + '\'' +
                '}';
    }
}